package com.elantra.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.elantra.base.CurrentUser;
import com.elantra.base.SystemManage;
import com.elantra.dao.ElantraLoginActionMapper;
import com.elantra.dao.ElantraLoginLogMapper;
import com.elantra.dao.ElantraUserMapper;
import com.elantra.entity.ElantraLoginAction;
import com.elantra.entity.ElantraLoginLog;
import com.elantra.entity.ElantraUser;
import com.elantra.service.LoginService;
import com.elantra.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private ElantraUserMapper elantraUserMapper;

    @Autowired
    private ElantraLoginLogMapper elantraLoginLogMapper;

    @Autowired
    private ElantraLoginActionMapper elantraLoginActionMapper;


    @Transactional
    @Override
    public JSONObject doLogin(String account, String pwd, String ip, String udid) {
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
            saveLoginFailLog(account, "", ip, udid, "账号密码", "pc", "请输入用户名和密码！");
            return R.To(false, null, "请输入用户名和密码！");
        }
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        ElantraUser elantraUser = elantraUserMapper.selectByMobile(account);
        if (elantraUser == null) {
            saveLoginFailLog(account, "", ip, udid, "账号密码", "pc", "用户名或密码错误！");
            return R.To(false, null, "用户不存在！");
        } else if (!Objects.equals(elantraUser.getPassword(), pwd)) {
            saveLoginFailLog(account, "", ip, udid, "账号密码", "pc", "密码错误！");
            return R.To(false, null, "密码错误！");
        } else if (elantraUser.getStatus() == 1) {
            saveLoginFailLog(account, "", ip, udid, "账号密码", "pc", "该账户已禁用！");
            return R.To(false, null, "用户未启用,请联系管理员！");
        }
        String token = saveLoginUser(elantraUser);
        ElantraLoginAction loginAction = elantraLoginActionMapper.getByUserAndPlatform(elantraUser.getId(), "pc");

        if (loginAction == null) {
            loginAction = new ElantraLoginAction();
            loginAction.setToken(token);
            loginAction.setLoginTime(new Date());
            loginAction.setUserId(elantraUser.getId());
            loginAction.setAccount(elantraUser.getAccount());
            loginAction.setMobile(elantraUser.getMobile());
            loginAction.setIp(ip);
            loginAction.setLoginMode("account");
            loginAction.setPlatformType("pc");
            loginAction.setUdid(udid);
            loginAction.setLoginTime(new Date());
            elantraLoginActionMapper.insert(loginAction);
        }else {
            loginAction.setUserId(elantraUser.getId());
            loginAction.setToken(token);
            loginAction.setLoginTime(new Date());
            loginAction.setLoginMode("account");
            elantraLoginActionMapper.updateByPrimaryKey(loginAction);
        }
        ElantraLoginLog elantraLoginLog=new ElantraLoginLog();
        elantraLoginLogMapper.insert(elantraLoginLog);
        Map<String,Object> resultMap=new HashMap<String,Object>();
        resultMap.put("token",token);
        resultMap.put("userId",elantraUser.getId());
        resultMap.put("account",elantraUser.getAccount());
        return R.To(true, resultMap, "登录成功！");
    }

    /**
     * 登录失败记录日志
     *
     * @param account   用户名
     * @param mobile    手机号
     * @param ip        ip地址
     * @param udid      设备标识
     * @param loginMode 登录模式
     * @param platform  平台
     * @param msg       错误原因
     */
    public void saveLoginFailLog(String account, String mobile, String ip, String udid, String loginMode, String platform, String msg) {
        ElantraLoginLog loginLog = new ElantraLoginLog();
        loginLog.setAccount(account);
        loginLog.setIp(ip);
        loginLog.setUdid(udid);
        loginLog.setMobile(mobile);
        loginLog.setStatus(new Byte("1"));
        loginLog.setMemo(msg);
        loginLog.setPlatform(platform);
        loginLog.setLoginMode(loginMode);
        elantraLoginLogMapper.insertSelective(loginLog);
    }

    /**
     * 缓存用户返回 token 将用户放入session 或 cache
     *
     * @param user 当前用户
     * @return token  这里默认为sessionid
     */
    public String saveLoginUser(ElantraUser user) {
        //获取项目菜单
        //用户存在 放入session 返回sessionid
        String token = SystemManage.getInstance().setCurrentUser(getCurrentUserByUser(user));
        return token;
    }

    public CurrentUser getCurrentUserByUser(ElantraUser user) {
        CurrentUser currentUser = new CurrentUser();
        currentUser.setUser(user);
//        //获取组织架构
//        SysOrganization org= organizationMapper.selectByPrimaryKey(user.getSysOrgId());
//        currentUser.setOrganization(org);
//        //获取部门
//        SysDepartment dept=departmentMapper.selectByPrimaryKey(user.getSysDepId());
//        currentUser.setDept(dept);
//
//        //获取菜单
//        List<SysMenu> menus=null;
//        //List<UserProMenuDto> proMenus=null;
//        //超级管理员
//        if(user.getUserType()==0){
//            menus=menuMapper.selectBySign(0);
//        }else{
//            menus=menuMapper.selectByUser(user.getId());
//        }
//        currentUser.setMenus(menus);
//
//        currentUser.setProMenus(getMenu(user.getId()));
        return currentUser;
    }
}
